//
//  KKOAuthViewController.swift
//  SinaWeiBo
//
//  Created by King.Kong. on 16/5/24.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

private let userInfoKey = "cn.kingkong.userInfoKey"

class KKOAuthViewController: UIViewController {

    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavBar()
        
        loadOauthPage()
    }

    private func loadOauthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id
        + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)!
        
        let req = NSURLRequest(URL: url)
        
        webView.loadRequest(req)
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
}

/// 设置导航条 监听按钮点击事件
extension KKOAuthViewController {
    
    
    @objc private func testAccount() {
        
        // JS注入
        let jsString = "document.getElementById('userId').value = '15612770058', document.getElementById('passwd').value = 'ufosof**123' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private func setNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(KKOAuthViewController.close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账户", target: self, action: #selector(KKOAuthViewController.testAccount))
 
    }
    
    
}
/// 显示加载进度
extension KKOAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD .show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
     
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString ?? ""
        
        let successFlag = "code="
        
        if urlString .containsString(successFlag) {
            
            // 授权成功
            let range = urlString.rangeOfString(successFlag)!
            let code = urlString.substringFromIndex(range.endIndex)
        
          KKUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) in
            if !isSuccess {
                
                SVProgressHUD.showWithStatus("世界上最遥远的距离就是没有网")
                return
            }
            
            /// 请求成功 切换视图控制器
//            UIApplication.sharedApplication().keyWindow?.rootViewController = KKWelcomeViewController()
//            NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            self.dismissViewControllerAnimated(false, completion: {
                
                //发出切换页面的通知
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            })

          })
            return false
        }
                
        return true
    }
}


